<template>
  <el-dialog :title="title" :visible.sync="visible" @closed="closedHandler">
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="name" label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item
        prop="description"
        label="角色描述"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 导入api
import { addRole, editRoleById } from '../../../api/setting'
export default {
  name: 'SettingDialog',
  data() {
    return {
      // 表单的数据
      form: {
        name: '',
        description: ''
      },
      // 左侧宽度
      formLabelWidth: '120px',
      // 是否显示弹框
      visible: false,
      // 表单校验
      rules: {
        name: [{ required: true, message: '角色名不能为空', trigger: 'blur' }],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      // if(this.form.id){
      //   return '编辑角色'
      // }else{
      //   return '新增角色'
      // }
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  methods: {
    closedHandler() {
      // console.log('关闭啦:')
      this.form = {
        name: '',
        description: ''
      }
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 判断走那个逻辑
          if (this.form.id) {
            // 编辑
            await editRoleById(this.form)
            this.$message.success('编辑成功')
          } else {
            // 新增
            await addRole(this.form)
            this.$message.success('新增成功')
          }
          // 关闭
          this.visible = false
          // 清空
          this.form = {
            name: '',
            description: ''
          }
          // 重新获取数据
          this.$parent.getData()
        } else {
          // 失败
          this.$message.error('格式有误,请检查!ღ( ´･ᴗ･` )比心')
          return false
        }
      })
    }
  }
}
</script>

<style></style>
